package com.foreknow.servlet;

import com.foreknow.bean.User;
import com.foreknow.service.UserService;
import com.foreknow.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "UserServletTest",urlPatterns = {"/user"})
public class UserServletTest extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String a = request.getParameter("a");
        if (a.equals("insertInfo")){
            insertInfo(request, response);
        }else if (a.equals("login")){
            login(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void insertInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String account = request.getParameter("account");
        String password = request.getParameter("password");
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String avatar = request.getParameter("avatar");
        Object[]objects={username,account,password,phone,email,avatar};
        UserService userService=new UserServiceImpl();
        boolean isRight = userService.addUser(objects);
        if (isRight){
            response.getWriter().write("注冊成功");
        }else{
            response.getWriter().write("注冊失敗");
        }
    }
    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取客户端的值
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //调用登录方法
        UserServiceImpl service=new UserServiceImpl();
        List<User> list = service.login(username, password);
        request.setAttribute("username",username);
        request.getRequestDispatcher("/user.jsp").forward(request,response);
    }
}
